//
//  EmitterView.m
//  Four_Fit_New
//
//  Created by lanou on 16/7/20.
//  Copyright © 2016年 xmaz. All rights reserved.
//

#import "EmitterView.h"
#import <QuartzCore/QuartzCore.h>

@interface EmitterView ()
@property (nonatomic, strong) CAEmitterLayer *emiLayer;
@end

@implementation EmitterView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupSubViews];
    }
    return self;
}

- (void)setupSubViews
{
    self.clipsToBounds = NO;
    self.userInteractionEnabled = NO;
    
    CAEmitterCell *emiCell = [CAEmitterCell emitterCell];
    emiCell.contents = (__bridge id)[UIImage imageNamed:@"Like-Sparkle"].CGImage;
    emiCell.name = @"thumb";
    emiCell.alphaRange = 0.2f;
    emiCell.alphaSpeed = -1.0f;
    emiCell.lifetime = 0.7f;
    emiCell.lifetimeRange = 0.3f;
    emiCell.birthRate = 0.0f;
    emiCell.velocity = 40.0f;
    emiCell.velocityRange = 10.0f;
    emiCell.emissionRange = M_PI_4;
    emiCell.scale = 0.05f;
    emiCell.scaleRange = 0.02f;
    
    _emiLayer = [CAEmitterLayer layer];
    _emiLayer.name = @"emitterLayer";
    _emiLayer.emitterShape = kCAEmitterLayerSphere;
    _emiLayer.emitterMode = kCAEmitterLayerOutline;
    _emiLayer.emitterPosition = self.center;
    _emiLayer.emitterSize = CGSizeMake(25, 0);
    _emiLayer.renderMode = kCAEmitterLayerOldestFirst;
    _emiLayer.masksToBounds = NO;
    _emiLayer.emitterCells = @[emiCell];
    _emiLayer.frame = [UIScreen mainScreen].bounds;
    [self.layer addSublayer:_emiLayer];
}

- (void)animate
{
    dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC);
    dispatch_after(delay, dispatch_get_main_queue(), ^{
        self.emiLayer.beginTime = CACurrentMediaTime();
        // 注意："emitterCells.xxx.birthRate" 第一、三个参数一定不能写错，中间可以自定义但是必须和emiCell.name的名字相同，否则不会产生放射动画效果
        CABasicAnimation *ani = [CABasicAnimation animationWithKeyPath:@"emitterCells.thumb.birthRate"];
        ani.fromValue = @(0);
        ani.toValue = @(500);
        [self.emiLayer addAnimation:ani forKey:nil];
    });
}

@end
